package com.lagou.demo.filter;

import com.lagou.demo.feign.UserFeignServiceI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class RequestFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserFeignServiceI userFeignService;

    private static final int MAX_TRY_COUNT = 5;
    private static final int TRY_COOLDOWN_PERIOD = 5;

    public static final Map<String, QueryInfo> QueryInfos = new ConcurrentHashMap();


    public class QueryInfo {
        private int tryCount;
        private Date tryCountTime;

        public QueryInfo () {
            this.tryCount = 0;
            this.tryCountTime = new Date();
        }


        public synchronized Boolean addCount() {
            if (this.tryCount < MAX_TRY_COUNT) {
                this.tryCount++;
                return true;
            } else {
                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.MINUTE, -1 * TRY_COOLDOWN_PERIOD);
                if (instance.getTime().getTime() - this.tryCountTime.getTime() > 0) {
                    this.tryCount = 0;
                    this.tryCountTime = new Date();
                    return true;
                }
            }
            return false;
        }

    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 若没有权限, 则跳转至登录页面
        URI uri = request.getURI();
//        if (uri.getPath().contains("/api/user/") || uri.getPath().contains("/api/code/")) {
            // ⽤用户微服务和验证码微服务的请求不不过滤（⽹网关调⽤用下游
            //⽤用户微服务的token验证接⼝口）
//            进⾏行行IP注册接⼝口的防暴暴刷控制，
        if (uri.getPath().contains("/api/code/create")) {
                // todo 错误码： 303，错误信息：您频繁进⾏注册，请求已被拒绝）
//            }
            String host = request.getRemoteAddress().getHostString();
            QueryInfo queryInfo = QueryInfos.get(host);
            queryInfo = queryInfo == null ? new QueryInfo(): queryInfo;
            Boolean aBoolean = queryInfo.addCount();
            QueryInfos.put(host, queryInfo);
            if (!aBoolean) {
                response.setStatusCode(HttpStatus.NOT_ACCEPTABLE); // 状态码
                log.debug("=====> 该地址 {}, 5 分钟内获取验证码超过5次, 已达到上限!", host);
                String data = "Request be denied! You have met the max count in 5 minites!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }

        } else {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> token = cookies.get("token");

            boolean valid;
            if (token == null) {
                valid = false;
                if (uri.getPath().contains("/api/user/login/")) {
                    valid = true;
                }
            } else {
                String info = userFeignService.info(token.get(0).getValue());
                valid = !StringUtils.isEmpty(info);
            }
            if (!valid) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====> 该请求token不合法, token 为:{}", token);
                String data = "Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
